<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class FormController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

	public function getPageList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $pageNo = $request->post("pageNo", 1);
        $pageSize = $request->post("pageSize", 10);
        $searchKey = $request->post("search", '');
        $res = DB::table('setting_form')->select("id", "name", "status", "create_time")->where("mall_id", $request->mallData['id']);
        if($searchKey != ''){
            $res->where(function ($query) use ($searchKey) {
                $query->where('name', 'LIKE', '%' . $searchKey . '%');
            });
        }
        $data = array(
            'total' => $res->count(),
            'rows' => $res->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("create_time", "desc")->get()
        );
        $data['rows'] = json_decode(json_encode($data['rows']),true);
        foreach ($data['rows'] as &$item){
            $item["create_time"] = date("Y-m-d H:i", $item["create_time"]);
        }
        $data['rows'] = $this->transferFields($data['rows']);
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    public function create(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $name = trim($request->post('name',''));
        if(empty($name)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "名称不能为空";
            return $this->return_result($this->returnData);
        }
        $formData = trim($request->post('formData',''));
        if(empty($formData)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "表单数据不能为空";
            return $this->return_result($this->returnData);
        }
        $status = $request->post('status', '');
        if($status == ''){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "状态不能为空";
            return $this->return_result($this->returnData);
        }
        $res = DB::table('setting_form')->insert([
            "name" => $name, "status" => $status, 'form_data' => $formData, 'create_time' => time(), "mall_id" => $request->mallData['id'],
            "item_id" => $request->itemId ?: 0, "option_id" => $request->optionId ?: 0
        ]);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '添加失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '添加成功';
        return $this->return_result($this->returnData);
    }

    public function getInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = DB::table('setting_form')->where(["id" => $request->id, "mall_id" => $request->mallData['id']])->first();
        $res = json_decode(json_encode($res),true);
        if($res){
            $res["form_data"] = json_decode($res["form_data"], true);
        }else{
            $res = [];
        }
        $res = $this->transferFields($res);
        $this->returnData['data'] = $res;
        return $this->return_result($this->returnData);
    }

    public function getAll(){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = DB::table('setting_form')->where(["status" => 1, "mall_id" => request()->mallData['id']])->select("id", "name")->get();
        $res = json_decode(json_encode($res),true);
        $this->returnData['data'] = $res ?: [];
        return $this->return_result($this->returnData);
    }

    public function edit(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $name = trim($request->post('name',''));
        if(empty($name)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "名称不能为空";
            return $this->return_result($this->returnData);
        }
        $formData = trim($request->post('formData',''));
        if(empty($formData)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "表单数据不能为空";
            return $this->return_result($this->returnData);
        }
        $status = $request->post('status', '');
        if($status == ''){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "状态不能为空";
            return $this->return_result($this->returnData);
        }
        $res = DB::table('setting_form')->where(["id" => $id, "mall_id" => $request->mallData['id']])->update([
            "name" => $name, "status" => $status, 'form_data' => $formData,
            "item_id" => $request->itemId ?: 0, "option_id" => $request->optionId ?: 0
        ]);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '修改成功';
        return $this->return_result($this->returnData);
    }

    public function delete(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(DB::table('apply_list')->where("form_id", $request->id)->count()){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '删除失败，表单已有申请列表';
            return $this->return_result($this->returnData);
        }
        $res = DB::table('setting_form')->where("id", $request->id)->delete();
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '删除失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '删除成功';
        return $this->return_result($this->returnData);
    }

    public function transferFields($data){
        if(empty($data)){
            return [];
        }
        if(is_array($data)){
            $newData = [];
            foreach ($data as $k => $v){
                if(!is_numeric($k)){
                    $k = Str::camel($k);
                }
                if(is_array($v)){
                    $v = $this->transferFields($v);
                }
                if(is_null($v)){
                    $v = '';
                }
                $newData[$k] = $v;
            }
            return $newData;
        }else{
            if(is_null($data)){
                return [];
            }else {
                return Str::camel($data);
            }
        }
    }
}